package com.xuxueli.applyModules.utils.testcharts;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * 表单字段验证工具类
 */
@Slf4j
public class FieldValidation {

    public static Validator getInstance() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        return factory.getValidator();
    }

    public static <T> void validate(T object) {
        if (object != null) {
            Set<ConstraintViolation<T>> validateSet = getInstance().validate(object);
            if (!CollectionUtils.isEmpty(validateSet)) {
                String messages = validateSet.stream()
                        .map(ConstraintViolation::getMessage)
                        .reduce((m1, m2) -> m1 + "；" + m2)
                        .orElse("参数输入有误！");
                throw new RuntimeException(messages);
            }
        }
    }
}